package com.srwl.mytx.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by dahai2070 on 2018/3/23 0023.
 */

public class IMFileTools {
    public static long deleteFile(String filePath) {
        try {
            return removeDir(filePath);
        } catch (Throwable var2) {
            var2.printStackTrace();
            return 0L;
        }
    }

    private static long removeDir(String filePath) {
        File f = new File(filePath);
        return removeFile(f);
    }

    private static long removeFile(File f) {
        if (null == f) {
            return 0L;
        } else {
            long size = 0L;
            if (f.isFile()) {
                size = f.length();
                f.delete();
                return size;
            } else {
                File[] flist = f.listFiles();
                if (null == flist) {
                    f.delete();
                    return size;
                } else {
                    for (int i = 0; i < flist.length; ++i) {
                        if (flist[i].isDirectory()) {
                            size += removeFile(flist[i]);
                        } else {
                            size += flist[i].length();
                            flist[i].delete();
                        }
                    }

                    f.delete();
                    return size;
                }
            }
        }
    }

    public static String writeBitmap(String path, String name, Bitmap bitmap, String type) {
        if (!TextUtils.isEmpty(path) && !TextUtils.isEmpty(name) && bitmap != null) {
            Bitmap.CompressFormat format = Bitmap.CompressFormat.JPEG;
            if ("PNG".equals(type)) {
                format = Bitmap.CompressFormat.PNG;
            }

            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }

            File _file = new File(path, name);
            if (_file.exists()) {
                _file.delete();
            }

            FileOutputStream fos = null;

            try {
                fos = new FileOutputStream(_file);
                bitmap.compress(format, 100, fos);
            } catch (FileNotFoundException var17) {
                var17.printStackTrace();
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                        return _file.getAbsolutePath();
                    } catch (IOException var16) {
                        var16.printStackTrace();

                    }
                }

            }
            return null;
        }
        return null;
    }

    public static void writeBitmap(String pathName, Bitmap bitmap, int compressRate) {
        if (null != bitmap && null != pathName) {
            boolean bPng = false;
            if (pathName.endsWith(".png")) {
                bPng = true;
            }

            File _file = new File(pathName);
            boolean bNew = true;
            if (_file.exists()) {
                bNew = false;
                _file = new File(pathName + ".tmp");
                _file.delete();
            }

            FileOutputStream fos = null;
            boolean bOK = false;

            try {
                fos = new FileOutputStream(_file);
                if (bPng) {
                    bitmap.compress(Bitmap.CompressFormat.PNG, compressRate, fos);
                } else {
                    bitmap.compress(Bitmap.CompressFormat.JPEG, compressRate, fos);
                }

                bOK = true;
            } catch (Exception var19) {
                var19.printStackTrace();
            } catch (Throwable var20) {
                var20.printStackTrace();
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                        if (!bNew && bOK) {
                            _file.renameTo(new File(pathName));
                        }
                    } catch (IOException var18) {
                        ;
                    }
                }

            }

        }
    }

    public static Bitmap readBitmap(String pathName) {
        return readBitmap(pathName, (BitmapFactory.Options) null);
    }

    public static Bitmap readBitmap(String pathName, BitmapFactory.Options options) {
        if (pathName == null) {
            return null;
        } else {
            InputStream in = FileUtils.readFile(pathName);
            if (in != null) {
                Bitmap bitmap = null;

                try {
                    bitmap = BitmapFactory.decodeStream(in, (Rect) null, options);
                } catch (OutOfMemoryError var6) {
                    var6.printStackTrace();

                } catch (Throwable var7) {

                    var7.printStackTrace();
                }

                try {
                    in.close();
                } catch (IOException var5) {
                    Log.w("IMFileTools", "readBitmap", var5);
                }

                return bitmap;
            } else {
                return null;
            }
        }
    }

    public static File createImageFile(String rootPath) {
        File file = new File(rootPath);
        File imageFile = null;
        if (!file.exists()) {
            file.mkdirs();
        }

        try {
            imageFile = File.createTempFile("image_" + System.currentTimeMillis(), ".jpg", file);
        } catch (IOException var4) {
            Log.w("IMFileTools", "createImageFile", var4);
        }

        return imageFile;
    }

    @SuppressLint({"NewApi"})
    public static Bitmap decodeBitmapWithBestSampleSize(String localName, Context context) {
        Bitmap bitmap = null;
        if (!TextUtils.isEmpty(localName) && (new File(localName)).isFile()) {
            int tryTime = 0;
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(localName, options);
            int actualWidth = options.outWidth;
            int actualHeight = options.outHeight;
            options.inJustDecodeBounds = false;
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
            options.inSampleSize = IMThumbnailUtils.findBestSampleSize(actualWidth, actualHeight, context.getResources().getDisplayMetrics().widthPixels, context.getResources().getDisplayMetrics().heightPixels);
            Log.d("IMFileTools@OriginalPic", "解析图片时 压缩幅度inSampleSize为" + options.inSampleSize);


            while (bitmap == null && tryTime < 9) {
                try {
                    bitmap = readBitmap(localName, options);
                } catch (OutOfMemoryError var7) {
                    Log.e("IMFileTools@OriginalPic", "decodeBitmap", var7);
                    //IMBitmapCache.clearCache();
                } catch (Throwable var8) {
                    Log.e("IMFileTools@OriginalPic", "decodeBitmap", var8);
                    // IMBitmapCache.clearCache();
                }

                ++tryTime;
                if (options != null && tryTime >= 3) {
                    if (options.inSampleSize >= 32) {
                        break;
                    }

                    int tempInSampleSize = options.inSampleSize * 2;
                    options.inSampleSize = Math.min(tempInSampleSize, 32);

                    Log.d("IMFileTools@OriginalPic", "内存不足时 尝试压缩幅度inSampleSize为" + options.inSampleSize);

                }
            }

            if (bitmap != null && options != null && Build.VERSION.SDK_INT >= 12) {
                ;
            }
        } else {
            Log.d("IMFileTools", "file doesn't exist ! @" + localName);
        }

        return bitmap;
    }

    public static boolean checkFileExists(String path) {
        File file = new File(path);
        return file.exists();
    }

}
